#!/usr/bin/env python
# coding: utf-8

import re

'''简单匹配'''
m1 = re.match(r'\d','2a')  #匹配，返回匹配对象_Match
m2 = re.search(r'\d','a2')  #匹配，返回匹配对象_Match
not_match1 = re.match(r'\d', 'aa') #不匹配，返回None
not_match2 = re.match(r'\d', 'a2') #不匹配，返回None
print(m1.group(0))   #2
print(m2.group(0))   #2
print(type(not_match1))   #<class 'NoneType'>
print(type(not_match2))   #<class 'NoneType'>

'''匹配分组'''
m = re.search(r'a(\d*)b(\d*)c','a22b11c')
print(m.group(0),m.group(1),m.group(2))  #a22b11c 22 11
print(m.groups()) #('22', '11')

'''分组中的引用'''
m1 = re.search(r'([a-zA-Z])2\1', 'o2o')        #匹配
not_match1 = re.search(r'([a-zA-Z])2\1', 'o2O')   #不匹配

m2 = re.search(r'(?P<foo>[a-zA-Z])2(?P=foo)@(?P<bar>\d+)-(?P=bar)', 'o2o@666-666')   #匹配
print(m2.group(0), m2.group(1), m2.group(2))      #o2o@666-666 o 666
print(m2.groupdict())  #{'foo': 'o', 'bar': '666'}

'''findall()获取一个字符串中的所有匹配，返回一个包含所有匹配的列表'''
m_list = re.findall(r'\d+','a = 100, b = 200, a + b = 300')
print(m_list)  #['100', '200', '300']

'''
匹配替换功能：
sub(pattern, replacement, string, count=0, flags=0)
用replacement替换string中匹配pattern的部分
replacement可以是字符串或替换函数；作为函数时，接收一个match对象作为函数的参数
'''
result = re.sub(r'\d', '2', "a = 1")
print(result)  # a = 2
result = re.sub(r'(th)is', r'\1at', "this is a question")
print(result)  # that is a question
result = re.sub(r'six', lambda m: m.group(0).upper(), "a big of six six six")
print(result) #666 SIX SIX SIX

'''
切割字符串
split(pattern, string, maxsplit=0, flags=0)
'''
result = re.split(r'"| ',r'183.6.132.235 - - [23/Aug/2017:11:22:46 +0800] "GET /centos6/repodata/3cfd6851e66bcbb66aab7b038c282d776ebfc35852bd27639b126ee64adf9285-other.sqlite.bz2 HTTP/1.1" 200 5112 "-" "urlgrabber/3.9.1 yum/3.2.29" "-"')
print(result)

'''
escape(pattern)
可以对包含正则字符串的字符串进行转义
'''
pattern = '[a-z]+'
print(re.escape(pattern)) # \[a\-z\]\+